package com.issc.framework;

import com.issc.framework.annotation.RequestMethod;
import com.issc.framework.bean.Data;
import com.issc.framework.bean.Param;
import com.issc.framework.bean.View;
import com.issc.framework.helper.*;
import com.issc.framework.util.Handler;
import com.issc.framework.util.JsonUtil;
import com.issc.framework.util.ReflectionUtil;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.*;

/**
 *
 */
@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {
    public DispatcherServlet() {
        super();
    }

    /**
     * 根据调用的方法得到当前的方法，根据方法的类型得到不同的返回类型
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取客户端输入的value的url和method的值
        String requestMethod = req.getMethod().toUpperCase();
        String requestPath = req.getPathInfo();
        //将得到的method转换成RequestMethod枚举类型
        RequestMethod method = RequestMethod.valueOf(requestMethod);
        //根据方法和请求路径得到对应的handler（类和对象的集合）
        Handler handler = ControllerHelper.getHandler(method, requestPath);
        if (requestPath.equals("/favicon.io")){
            return;
        }
        if (handler != null) {
            //获取handler的key（即ControllerClass类）
            Class<?> controllerClass = handler.getControllerClass();
            //根据获得的类得到该类的实例
            Object controllerBean = BeanHelper.getBeanInstance(controllerClass);
            Param param = null;
            //FileItemFactory factory = new DiskFileItemFactory();
            if (ServletFileUpload.isMultipartContent(req)) {
                //ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
               param= FileUploadHelper.createParam(req);
            } else {
               param= FileUploadHelper.getParam(req);
            }
            //Param param = new Param(paramMap);
            //获取Handler方法
            Method requestMappingMethod = handler.getHandlerMethod();
            Object result;
            if (requestMappingMethod.getParameterCount()==0) {
                result = ReflectionUtil.invokeMethod(controllerBean, requestMappingMethod);
            }else {
                //调用该方法
                result = ReflectionUtil.invokeMethod(controllerBean, requestMappingMethod, param);
            }
            //判断方法的类型
            if (result instanceof View) {
                handleViewResult((View) result, req, resp);
            } else if (result instanceof Data) {
                handleDataResult((Data) result, resp);
            }
        }
    }


    /**
     * 初始化类以及注册Jsp和应用基础路径
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        //初始化框架相关的所有Helper类
        HelperLoader.init();
        //注册
        ServletContext servletContext = config.getServletContext();

        ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
        jspServlet.addMapping(ConfigHelper.getAppJspPath() + "*");


        ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
        defaultServlet.addMapping(ConfigHelper.getAppAssetPath() + "*");

        FileUploadHelper.init(servletContext);

    }

    private void handleViewResult(View view, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String path = view.getPath();
        if (!path.isEmpty()) {
            if (path.startsWith("/")) {
                resp.sendRedirect(path);
            } else {
                Map<String, Object> model = view.getModel();
                for (Map.Entry<String, Object> entry : model.entrySet()) {
                    req.setAttribute(entry.getKey(), entry.getValue());
                }
                //请求转发跳转jsp页面
                req.getRequestDispatcher(ConfigHelper.getAppJspPath() + path).forward(req, resp);
            }
        }
    }

    private void handleDataResult(Data data, HttpServletResponse resp) {
        Object model = data.getModel();
        if (model != null) {
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            PrintWriter printWriter = null;
            try {
                printWriter = resp.getWriter();
                String json = JsonUtil.toJson(model);
                printWriter.write(json);
                printWriter.flush();
                printWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
